from django.http import HttpResponse
from django.http import HttpResponseRedirect

import os
import win32api
import win32con
import win32gui
import win32ui

import subprocess
import configparser
from django.shortcuts import render
import numpy as np
from PIL import ImageGrab
import cv2

config = configparser.ConfigParser()
path = 'screenshot.ini'
config.read(path)
uploadFolder = config['realTime']['uploadFolder']
seeFolder = config['realTime']['seeFolder']
program = int(config['screenshot']['program'])
fName = f'{uploadFolder}/screenshot.jpg'


# 打开初始界面
def OpenWeb(request):
    request.encoding = 'utf-8'
    return render(request, "shutDown.html")


# 关机
def shutDown(request):
    time = int(request.GET['time']) * 60
    cmds = f"shutdown -s -t {time}"
    print(cmds)
    subprocess.Popen(cmds, shell=True, stdout=subprocess.PIPE)
    return render(request, "shutDownSuccess.html")


# 取消关机
def CancelShutDown(request):
    cmds = "shutdown -a"
    print(cmds)
    subprocess.Popen(cmds, shell=True, stdout=subprocess.PIPE)
    return render(request, "shutDown.html")


# 重启
def restart(request):
    time = int(request.GET['time']) * 60
    cmds = f"shutdown -r -t {time}"
    print(cmds)
    subprocess.Popen(cmds, shell=True, stdout=subprocess.PIPE)
    return render(request, "shutDownSuccess.html")


# 获取电脑截图
def realTimeScreenshot(request):
    if program == 1:
        window_capture(fName)
    elif program == 2:
        screenshot_imageGrab(fName)
    return render(request, "screenshot.html", context={'ScreenshotUrl': f'/{seeFolder}/screenshot.jpg'})


# 删除截图
def reBack(request):
    try:
        os.remove(fName)
    except BaseException as e:
        print(e)
    return render(request, "shutDown.html")


# 获取电脑截图主方法(压缩图)
def screenshot_imageGrab(filename):
    img = ImageGrab.grab()
    img = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 3)
    img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
    cv2.imwrite(filename, img)


# 获取电脑截图主方法(高清图)
def window_capture(filename):
    hwnd = 0
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)

# python manage.py runserver 0.0.0.0:80

# pip freeze > requirements.txt
# pip install -r requirements.txt
